package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.CacheConstant;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description RoleServiceImpl
 * @Author xxxx
 * @Date 2024-10-24
 */

@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {

    private final RoleMapper roleMapper;
    private final RoleResourceMapper roleResourceMapper;
    private final UserRoleMapper userRoleMapper;

    /**
     * 角色分页查询
     * @param roleDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResponse<RoleVo> findRoleVoPage(RoleDto roleDto, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Page<RoleVo> page = roleMapper.getByPage(roleDto);
        //将page封装给PageResponse<RoleVo>
        return PageResponse.of(page,RoleVo.class);
    }

    /**
     * 角色保存
     * @param roleDto
     */
    @Override
    public void createRole(RoleDto roleDto) {

        //将roleDto转换为role对象
        Role role = BeanUtil.toBean(roleDto, Role.class);

        //调用mapper添加角色
        roleMapper.insertSelective(role);
    }

    /**
     * 根据角色查询选中的资源数据
     * @param roleId
     * @return
     */
    @Override
    public Set<String> findCheckedResources(Long roleId) {
        return roleResourceMapper.findCheckedResources(roleId);
    }

    /**
     * 角色修改
     * @param roleDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(RoleDto roleDto) {
        //1.将roleDto转换为role对象
        Role role = BeanUtil.toBean(roleDto, Role.class);

        //2.调用mapper直接修改角色单表数据（解决编辑角色，启用或禁用）
        //2.1判断是否操作为禁用
        if (SuperConstant.DATA_STATE_1.equals(role.getDataState())) {
            //2.1.1获取角色分配用户的数量
            Integer count = userRoleMapper.findCountByRoleId(role.getId());
            //2.1.2数量大于0，抛出异常，该角色关联用户不可以禁用
            if (count>0){
                throw new RuntimeException("该角色已分配用户，不能被禁用");
            }
        }
        //2.2直接修改
        roleMapper.updateByPrimaryKeySelective(role);

        //3.判断用户是否传递了分配资源编号集合数据（如果有关联的资源编号说明前端是点击菜单权限分配保存按钮）
        //3.1 不为null并且数组长度大于0
        String[] checkedResourceNos = roleDto.getCheckedResourceNos();
        if (checkedResourceNos != null && checkedResourceNos.length > 0) {
            //3.1.1 先删除角色关联的资源中间表数据
            roleResourceMapper.deleteByRoleId(role.getId());
            //3.1.2 封装构建中间表集合数据List<RoleResource>
            List<RoleResource> roleResourceList = Arrays.stream(checkedResourceNos).map(resourceNo -> {
                return RoleResource.builder()
                        .roleId(role.getId())
                        .resourceNo(resourceNo)
                        .dataState(SuperConstant.DATA_STATE_0)
                        .build();
            }).collect(Collectors.toList());
            //3.1.3 将中间表集合数据List<RoleResource>批量插入中间表中
            roleResourceMapper.batchInsert(roleResourceList);
        }else if (checkedResourceNos != null){
            //3.2 不为null并且数组长度等于0，抛出异常，提示用户请勾选分配的资源
            throw  new RuntimeException("请勾选分配的资源");
        }
    }

    /**
     * 删除角色相关信息
     * @param roleId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void remove(Long roleId) {

        //删除角色信息
        roleMapper.deleteByPrimaryKey(roleId);

        //删除用户角色关联信息
        userRoleMapper.deleteByRoleId(roleId);

        //删除角色资源关联信息
        roleResourceMapper.deleteByRoleId(roleId);
    }

    /**
     * 角色下拉框
     * @return
     */
    @Override
    public List<RoleVo> roleDropdownMenu() {
        List<RoleVo> roleVo = roleMapper.roleDropdownMenu();
        return roleVo;
    }
}
